#!/usr/bin/env python

import sys
import time
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, backref, sessionmaker

sys.path.append(".")
sys.path.append("..")
import env
import process

import models

TIMEOUT_UPDATE = 10

class Test:
    
    def __init__(self):
        self.engine = create_engine('sqlite:///' + sys.path[0] + '/data.sqlite', echo=True)
        models.metadata.create_all(self.engine)
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
    
    def update(self):
        ps_latest_list = process.Process.latest()
        apps = []
        for p in ps_latest_list:
            app = self.session.query(models.Application).filter_by(name=p.command).first()
            if not app:
                app = models.Application(p.command)
                self.session.add(app)
            apps.append(app)
        t = models.Trace(**(env.get()))
        for app in apps:
            t.apps.append(app)
        self.session.commit()

    def run(self):
        while True:
            self.update()
            time.sleep(TIMEOUT_UPDATE)
            
    
if __name__ == '__main__':
    Test().run()